package com.yedean.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yedean.mall.dto.UmsMenuNode;
import com.yedean.mall.entity.UmsMenu;
import com.yedean.mall.mapper.UmsMenuMapper;
import com.yedean.mall.service.IUmsMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台菜单表 服务实现类
 * </p>
 *
 * @author yedean
 * @since 2022-08-03
 */
@Service
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements IUmsMenuService {

    @Resource
    UmsMenuMapper umsMenuMapper;
    

    @Override
    public List<UmsMenuNode> treeList() {
        List<UmsMenu> umsMenus = umsMenuMapper.selectList(null);
        //把数组菜单数据转化成树节点
        return umsMenus.stream()
                .filter(umsMenu -> umsMenu.getLevel() == 0)
                .map(umsMenu -> covertMenu(umsMenu, umsMenus))
                .collect(Collectors.toList());
    }

    @Override
    public IPage<UmsMenu> pageList(Long parentId, Integer pageSize, Integer pageNum) {
        //分页
        IPage<UmsMenu> page = new Page<>(pageNum, pageSize);

        //组装查询条件
        QueryWrapper<UmsMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);

        return umsMenuMapper.selectPage(page, wrapper);
    }

    @Override
    public void updateHidden(Long id, Integer hidden) {
        UmsMenu umsMenu = new UmsMenu();
        umsMenu.setId(id);
        umsMenu.setHidden(hidden);
        umsMenuMapper.updateById(umsMenu);
    }


    private UmsMenuNode covertMenu(UmsMenu umsMenu, List<UmsMenu> umsMenus) {
        UmsMenuNode node = new UmsMenuNode();
        //复制值
        BeanUtil.copyProperties(umsMenu, node);

        //递归寻找子节点
        List<UmsMenuNode> children = umsMenus.stream()
                .filter(subMenu -> subMenu.getParentId().equals(umsMenu.getId()))
                .map(subMenu -> covertMenu(subMenu, umsMenus))
                .collect(Collectors.toList());

        node.setChildren(children);
        return node;
    }


}
